<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('page.system.userRole.assignRole')"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="user-role-assign">
      <!-- 用户选择区域 -->
      <div class="user-section">
        <h4>{{ $t('page.system.userRole.selectUser') }}</h4>
        <div v-if="filteredUsers.length === 0" class="empty-state">
          <p>{{ $t('page.system.userRole.noAvailableUsers') }}</p>
        </div>
        <el-table
          v-else
          v-loading="userLoading"
          :data="filteredUsers"
          border
          stripe
          max-height="300px"
          @selection-change="handleUserSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="username"
            :label="$t('page.system.userRole.username')"
            min-width="100"
          />
          <el-table-column
            prop="realName"
            :label="$t('page.system.userRole.realName')"
            min-width="100"
          />
          <el-table-column
            prop="email"
            :label="$t('page.system.userRole.email')"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            :label="$t('page.system.userRole.selectedRoles')"
            min-width="200"
          >
            <template #default="{ row }">
              <el-tag
                v-for="role in row.roles || []"
                :key="role.id"
                size="small"
                class="mr-1"
              >
                {{ role.name }}
              </el-tag>
              <span v-if="!row.roles || row.roles.length === 0" class="text-gray-400">
                无角色
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 角色选择区域 -->
      <div class="role-section" style="margin-top: 20px;">
        <h4>{{ $t('page.system.userRole.selectRole') }}</h4>
        <div class="role-grid">
          <el-checkbox-group v-model="selectedRoleIds">
            <div class="grid grid-cols-3 gap-2">
              <el-checkbox
                v-for="role in availableRoles"
                :key="role.id"
                :label="role.id"
                class="role-checkbox"
              >
                <div class="role-item">
                  <div class="role-name">{{ role.name }}</div>
                  <div class="role-key">{{ role.roleKey }}</div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 选择摘要 -->
      <div class="summary-section" style="margin-top: 20px;">
        <el-alert
          :title="`已选择 ${selectedUsers.length} 个用户，${selectedRoleIds.length} 个角色`"
          type="info"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('page.system.userRole.cancel') }}
        </el-button>
        <el-button 
          type="primary" 
          :loading="assignLoading" 
          :disabled="selectedUsers.length === 0 || selectedRoleIds.length === 0"
          @click="handleAssign"
        >
          {{ $t('page.system.userRole.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import {
  ElAlert,
  ElButton,
  ElCheckbox,
  ElCheckboxGroup,
  ElDialog,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { Role } from '#/api/system/role';
import { getAllRolesApi } from '#/api/system/role';
import type { UserInfo, UserRoleAssignParams } from '#/api/system/userRole';
import { assignUserRolesApi } from '#/api/system/userRole';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  users: UserInfo[];
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const userLoading = ref(false);
const assignLoading = ref(false);
const availableRoles = ref<Role[]>([]);
const selectedUsers = ref<UserInfo[]>([]);
const selectedRoleIds = ref<number[]>([]);

// 过滤用户列表（可以根据需要添加搜索功能）
const filteredUsers = computed(() => {
  console.log('UserRoleAssignModal - 接收到的用户列表数量:', props.users.length);
  console.log('UserRoleAssignModal - 用户列表:', props.users);
  console.log('UserRoleAssignModal - filteredUsers 计算结果:', props.users.length === 0 ? '用户列表为空' : '用户列表正常');
  return props.users;
});

// 获取所有角色
const getAllRoles = async () => {
  try {
    const roles = await getAllRolesApi();
    availableRoles.value = roles.filter(role => role.status === 0); // 只显示正常状态的角色
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      getAllRoles();
      // 重置选择状态
      selectedUsers.value = [];
      selectedRoleIds.value = [];
    }
  }
);

// 处理用户选择变更
const handleUserSelectionChange = (selection: UserInfo[]) => {
  selectedUsers.value = selection;
};

// 分配角色
const handleAssign = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning($t('page.system.userRole.message.selectUserFirst'));
    return;
  }

  if (selectedRoleIds.value.length === 0) {
    ElMessage.warning($t('page.system.userRole.message.selectRoleFirst'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      $t('page.system.userRole.message.assignConfirm'),
      $t('page.system.userRole.assignRole'),
      {
        type: 'warning',
      }
    );

    assignLoading.value = true;

    // 批量为每个用户分配角色
    const promises = selectedUsers.value.map(user => {
      const params: UserRoleAssignParams = {
        userId: user.id,
        roleIds: selectedRoleIds.value,
      };
      return assignUserRolesApi(params);
    });

    await Promise.all(promises);

    ElMessage.success($t('page.system.userRole.message.assignSuccess'));
    emit('success');
    handleClose();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('分配角色失败:', error);
    }
  } finally {
    assignLoading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  selectedUsers.value = [];
  selectedRoleIds.value = [];
  dialogVisible.value = false;
};
</script>

<style scoped>
.user-role-assign {
  max-height: 600px;
  overflow-y: auto;
}

.user-section,
.role-section,
.summary-section {
  margin-bottom: 20px;
}

.user-section h4,
.role-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-weight: 600;
}

.role-grid {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.role-checkbox {
  margin: 0 !important;
  width: 100%;
}

.role-item {
  display: flex;
  flex-direction: column;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  transition: all 0.3s;
}

.role-item:hover {
  border-color: #409eff;
}

.role-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.role-key {
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

.mr-1 {
  margin-right: 4px;
}

.text-gray-400 {
  color: #909399;
}

.grid {
  display: grid;
}

.grid-cols-3 {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.gap-2 {
  gap: 8px;
}
</style> 
